import React, { useState } from 'react';
import { Modal, Button, Upload, message, Input, Progress, Tooltip } from 'antd';
import { UploadOutlined, DownloadOutlined, CloseOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { IconButton, Iconify, SvgIcon } from '@/components/icon';

import { useThemeToken } from '@/theme/hooks';

import appService from '@/api/services/appService';
import axios from 'axios';
import { useLocation } from 'react-router-dom';

interface BatchImportModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: () => void;
}

const BatchImportModal: React.FC<BatchImportModalProps> = ({ visible, onCancel, onOk }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [fileName, setFileName] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const { colorPrimary, colorSuccess, colorBgBase, colorBgLayout } = useThemeToken();
  const [progress, setProgress] = useState();
  const [isRuning, setIsRuning] = useState(0);
  const [isStop, setIsStop] = useState(false);

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || "";

  const handleDownload = () => {
    axios({
      url: '/openapi/v1/extension/download/template',
      method: 'GET',
      responseType: 'blob',
    })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'template.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('模板下载成功');
      })
      .catch((error) => {
        console.error('下载失败:', error);
        message.error('模板下载失败');
      });
  };

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.error('请先选择文件');
      return;
    }

    try {
      setLoading(true);
      const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('app_id', appId);
      const response = await appService
        .extensionBatchCreate(formData)
        .then((resp) => {
          console.log(resp);
          const messageText = typeof resp === 'object' && resp.message ? resp.message : '导入成功';
          message.success(messageText);
        })
        .finally(() => {
          setLoading(false);
        });
      console.log(response);

      await pollUntilComplete(appService.extensionBatchCreateStatus, 2000);
    } catch (error) {
      console.error('上传失败:', error);
      message.error('业务导入失败');
    } finally {
      setLoading(false);
    }
  };

  const pollUntilComplete = async (getStatus, interval) => {
    let completed = false;
    const intervalId = setInterval(async () => {
      try {
        const res = await getStatus(appId);
        console.log(res);
        setIsRuning(res.isRuning);
        setProgress(res.progress);

        if (res.progress === 100) {
          completed = true;
          clearInterval(intervalId); // 清除定时器
          setIsRuning(0);
          setIsStop(false);

          setFileList([]);
          setFileName('');
          onOk();

          setTimeout(() => {
            message.success('共' + res.total + '个业务，成功导入' + res.success);
          }, 0);
        }
      } catch (error) {
        console.error('获取状态失败:', error);
        clearInterval(intervalId); // 如果获取状态失败，也清除定时器
        throw error; // 抛出错误以便上层 catch 处理
      }
    }, interval);

    return new Promise((resolve, reject) => {
      if (completed) resolve();
    });
  };

  const onStop = () => {
    appService.extensionBatchCreateTerminate(appId).then((res) => {
      console.log('onStop', res);
      setTimeout(() => {
        message.success('终止导入成功');
      }, 0);

      setIsStop(true);
    });
  };

  const onDelete = () => { };

  const onRefresh = () => { };

  const handleClearInput = () => {
    setFileName(''); // 清空文件名
    setFileList([]); // 清空文件列表
  };

  const uploadProps: UploadProps = {
    name: 'file',
    fileList: fileList,
    showUploadList: false,
    accept: '.xlsx, .xls, .csv', // 限制只能选择 Excel 文件
    beforeUpload(file) {
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'; // 支持 .xlsx 和 .xls 文件
      if (!isExcel) {
        message.error('仅支持上传 Excel 文件');
      } else {
        setFileList([file]);
        setFileName(file.name); // 更新文件名到输入框
      }
      return false;
    },
    onChange(info) {
      if (info.file.status === 'removed') {
        setFileList([]);
        setFileName(''); // 清空文件名
      }
    },
  };

  return (
    <Modal
      title="批量导入"
      visible={visible}
      onOk={handleUpload}
      onCancel={() => {
        setFileList([]);
        setFileName('');
        onCancel();
      }}
      footer={[
        <Button
          key="cancel"
          onClick={() => {
            setFileList([]);
            setFileName('');
            onCancel();
          }}
          className="!rounded-button"
        >
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={handleUpload}
          loading={loading} // 绑定 loading 状态
          className="!rounded-button bg-purple-600 hover:bg-purple-700"
        >
          确定
        </Button>,
      ]}
    >
      <div className="rounded-lg pb-8 pt-8 shadow-sm">
        <div className="mb-2 flex items-center">
          <Input
            value={fileName}
            readOnly
            placeholder="请选择文件"
            className="!rounded-button squere-input  h-10 flex-1"
            style={{ borderRadius: '2px' }}
            suffix={
              fileName && ( // 当有文件名时显示清空按钮
                <CloseOutlined
                  onClick={handleClearInput}
                  style={{ color: 'rgba(0, 0, 0, 0.25)', cursor: 'pointer' }}
                />
              )
            }
          />
          <Upload {...uploadProps} className="w-auto">
            <Button
              // icon={<UploadOutlined />}
              className="!rounded-button border border-gray-300 bg-gray-100 text-gray-700 hover:bg-gray-200"
              type="primary"
              style={{
                borderRadius: '2px',
                height: '40px',
              }}
            >
              点击选择
            </Button>
          </Upload>
        </div>
        {isRuning != 0 && (
          <div
            style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
            className="mb-2"
          >
            <div style={{ width: '100%' }}>
              {isStop == false && <Progress
                percent={progress}
                strokeColor={{ from: colorPrimary, to: colorSuccess }}
                trailColor="transparent"
                status="active"
              />}
            </div>
            <div className="ml-2 mt-1 flex items-center space-x-2">
              {/* <Tooltip title="删除" placement="bottom">
                <Button
                  shape="circle"
                  style={{ border: 'none' }}
                  onClick={() => {
                    onDelete();
                  }}
                >
                  <SvgIcon icon="ic-delete" size={15} />
                </Button>
              </Tooltip> */}
              {isStop == false && (
                <Tooltip title="停止" className="flex items-center justify-center">
                  <Button
                    shape="circle"
                    style={{ border: 'none' }}
                    onClick={() => {
                      onStop();
                    }}
                  >
                    <SvgIcon icon="ic-pause" size={20} />
                  </Button>
                </Tooltip>
              )}
              {/* {isStop == true && (
                <Tooltip title="重试">
                  <Button
                    shape="circle"
                    style={{ border: 'none' }}
                    onClick={() => {
                      onRefresh();
                    }}
                  >
                    <SvgIcon icon="ic-retry" size={20} />
                  </Button>
                </Tooltip>
              )} */}
            </div>
          </div>
        )}

        <div
          className="text-blue-600 mt-2 inline-flex cursor-pointer items-center"
          onClick={handleDownload}
        >
          <DownloadOutlined
            className="mr-2"
            style={{
              color: colorPrimary,
            }}
          />
          <span
            className='text-primary'
          >
            模板下载
          </span>

          {/* <span
            style={
              {
                // color: 'grey',
              }
            }
            className="ml-3 text-gray-400"
          >
            选中多个Excl模板上传 就可一次导入多个业务
          </span> */}
        </div>
      </div>
    </Modal>
  );
};

export default BatchImportModal;
